﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Telerik.Windows.Controls;

namespace JustinAngel.MindwaveSensor.WP8.TestApp
{
    public partial class LineChartMindwaveData : PhoneApplicationPage
    {
        public LineChartMindwaveData()
        {
            InitializeComponent();

            InitSeries(0, "Delta");
            InitSeries(1, "Theta");
            InitSeries(2, "AlphaLow");
            InitSeries(3, "AlphaHigh");
            InitSeries(4, "BetaLow");
            InitSeries(5, "BetaHigh");
            InitSeries(6, "GammaLow");
            InitSeries(7, "GammaMid");
        }

        private ObservableCollection<MindwaveReading> mindsetPoints = new ObservableCollection<MindwaveReading>();

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (Mindwave.Current.IsDataValid)
            {
                mindsetPoints.Add(Mindwave.Current.CurrentValue);
            }

            Mindwave.Current.CurrentValueChanged += Current_CurrentValueChanged;

            base.OnNavigatedTo(e);
        }


        void Current_CurrentValueChanged(object sender, MindwaveReadingEventArgs e)
        {
            if (e.SensorReading.IsDataReliable)
            {
                mindsetPoints.Add(e.SensorReading);
            }
        }

        protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
        {
            Mindwave.Current.CurrentValueChanged -= Current_CurrentValueChanged;
        }

        private void InitSeries(int index, string propertyName)
        {
            chart.Series[index].ItemsSource = mindsetPoints;
            ((LineSeries)chart.Series[index]).ValueBinding = new PropertyNameDataPointBinding(propertyName);
            ((LineSeries)chart.Series[index]).CategoryBinding = new PropertyNameDataPointBinding("Timestamp");
        }
    }
}